﻿using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web.Mvc;

namespace Sample.Common.Validation
{
    public class NotEqualAttribute : ValidationAttribute, IClientValidatable
    {
        public NotEqualAttribute(string NotEqualValue)
        {
            this.NotEqualValue = NotEqualValue;
        }

        public override string FormatErrorMessage(string name)
        {
            return string.Format("{0}不能够等于 {1}", name, NotEqualValue);
        }
        public string NotEqualValue { get; private set; }

        public IEnumerable<ModelClientValidationRule>
               GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
        {
            var validationRule = new ModelClientValidationRule
            {
                ErrorMessage = FormatErrorMessage(metadata.DisplayName),
                ValidationType = "notequal",
            };
            validationRule.ValidationParameters.Add("value", NotEqualValue);

            yield return validationRule;
        }

        public override bool IsValid(object value)
        {
            if (value == null) return true;
            return this.NotEqualValue != value.ToString();
        }

        #region IClientValidatable Members

        IEnumerable<System.Web.Mvc.ModelClientValidationRule> IClientValidatable.GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
        {
            throw new NotImplementedException();
        }

        #endregion
    }
}
